
class IyfInfo extends AbstractPlugin {

  static BASE_URL = 'https://www.iyf.tv';

  async fetchWebsiteInfo() {
    const url = window.location.href;

    const parsedUrl = new URL(url);
    const pathSegments = parsedUrl.pathname.split('/');
    const vid = pathSegments[pathSegments.length - 1];
    let id = parsedUrl.searchParams.get('id');

    const [publicKey, privateKey] = this.getKeysFromBody(document.body.outerHTML);

    const sign_url = getSignUrl(
      `https://m10.iyf.tv/v3/video/languagesplaylist?cinema=1&vid=${vid}&lsk=1&taxis=1&cid=0,1`,
      publicKey, privateKey
    );

    const http_headers = {
      'User-Agent': IyfInfo.DEFAULT_USER_AGENT,
      'Referer': id ? `${IyfInfo.BASE_URL}/play/${vid}?id=${id}` : `${IyfInfo.BASE_URL}/play/${vid}`,
      'Origin': IyfInfo.BASE_URL,
    };
    const result = await doHttpRequestSync(sign_url, { headers: http_headers });
    if(result.status !== 'success' || /error code/.test(result.body)) {
      return null;
    }
    const playSources = [];
    const html = result.body;
    try {
      // play sites data
      const results = JSON.parse(html);
      if(typeof(results) === 'object' && results !== null) {
        if(results.hasOwnProperty('data') && results.data.hasOwnProperty('info') && Array.isArray(results.data.info)
            && results.data.info.length > 0 && results.data.info[0].hasOwnProperty('playList')) {
          const episodes = [];
          results.data.info[0].playList.forEach((episodeItem, index) => {
            if(!episodeItem.hasOwnProperty('name') && !episodeItem.hasOwnProperty('key')) return;
            episodes.push(new Episode({
              title: episodeItem.name,
              link: `${IyfInfo.BASE_URL}/play/${vid}?id=${episodeItem.key}`
            }));
          });
          playSources.push(new Source({
            title: '爱壹帆',
            episodes: episodes
          }));
        }
      }
    } catch (e) {
      return null;
    }

    const websiteInfo = new WebsiteInfo();
    websiteInfo.type = 'video';
    const match = document.body.outerHTML.match(/<meta name="title" content="([^"]*)"/);
    if(match && match[1]) {
      const content = match[1];
      websiteInfo.title = content.split('-')[0];
    }
    websiteInfo.link = url;
    websiteInfo.sources = playSources;

    if(playSources && playSources.length > 0) {
      if(id) {
        [websiteInfo.sourceIndex, websiteInfo.episodeIndex] = AbstractPlugin.findEpisode(playSources, url);
      } else {
        websiteInfo.sourceIndex = 0;
        websiteInfo.episodeIndex = 0;
        const idMatch = playSources[0].episodes[0].link.match(/[?&]id=([^&]+)/);
        if(idMatch) {
          id = idMatch[1];
        }
      }
      websiteInfo.playUrl = await this.getPlayableUrl(vid, id, publicKey, privateKey);
    }

    return websiteInfo;
  }

  async fetchPlayUrlInfo(url) {
    const parsedUrl = new URL(url);
    const pathSegments = parsedUrl.pathname.split('/');
    const vid = pathSegments[pathSegments.length - 1];
    const id = parsedUrl.searchParams.get('id');

    const http_headers = {
      'User-Agent': IyfInfo.DEFAULT_USER_AGENT,
      'Referer': url,
      'Origin': IyfInfo.BASE_URL,
    };
    const result = await doHttpRequestSync(url, { headers: http_headers });
    if(result.status !== 'success') {
      return null;
    }
    const [publicKey, privateKey] = this.getKeysFromBody(result.body);

    return this.getPlayableUrl(vid, id, publicKey, privateKey);
  }

  async getPlayableUrl(vid, id, publicKey, privateKey) {
    let playInfoUrl;
    if(id) {
      playInfoUrl = `https://m10.iyf.tv/v3/video/play?cinema=1&id=${id}&a=0&usersign=1&region=GL.&device=1&isMasterSupport=1`;
    } else {
      playInfoUrl = `https://m10.iyf.tv/v3/video/play?cinema=1&id=${vid}&a=1&usersign=1&region=GL.&device=1&isMasterSupport=1`;
    }
    const signUrl = getSignUrl(playInfoUrl, publicKey, privateKey);

    function isIyfDomain(url) {
      return /https?:\/\/[^/]*\.iyf\.tv/.test(url);
    }

    const http_headers = {
      'User-Agent': IyfInfo.DEFAULT_USER_AGENT,
      'Referer': id ? `${IyfInfo.BASE_URL}/play/${vid}?id=${id}` : `${IyfInfo.BASE_URL}/play/${vid}`,
      'Origin': IyfInfo.BASE_URL,
    };
    const result = await doHttpRequestSync(signUrl, { headers: http_headers });
    if(result.status !== 'success' || /error code/.test(result.body)) {
      return null;
    }

    const body = JSON.parse(result.body);
    const data = body?.data?.info?.[0]?.flvPathList;

    if(!data) return null;

    let defaultUrl = null;
    const playBackupUrls = [];
    let playBackupIndex = 0;

    for(const item of data) {
      if(item.isHls) {
        const keys = ["result", "dashResult", "backup", "rtmp"];
        for(const key of keys) {
          if(item[key]) {
            const playUrl = getSignUrl(item[key], publicKey, privateKey);
            if(!defaultUrl) {
              defaultUrl = playUrl;
            } else if (defaultUrl !== playUrl && !playBackupUrls.includes(playUrl)) {
              // Check if the domain for URLs is different
              if(isIyfDomain(defaultUrl) && !isIyfDomain(playUrl)) {
                playBackupUrls.splice(playBackupIndex, 0, defaultUrl);
                playBackupIndex++;
                defaultUrl = playUrl;
              } else {
                playBackupUrls.splice(playBackupIndex, 0, playUrl);
                playBackupIndex++;
              }
            }
          }
        }

        const playUrl = new PlayUrlInfo();
        playUrl.type = 'video';
        playUrl.urls = [defaultUrl];
        playUrl.backupUrls = playBackupUrls;
        return playUrl;
      }
    }
    return null;
  }

  getKeysFromBody(body) {
    const injectJsonMatch = body.match(/var injectJson = (.*?);/);
    if(injectJsonMatch && injectJsonMatch[1]) {
      const injectJson = JSON.parse(injectJsonMatch[1]);
      if(injectJson.hasOwnProperty('config') && Array.isArray(injectJson.config) && injectJson.config.length > 0) {
        const config = injectJson.config[0];
        if(config.hasOwnProperty('pConfig') && config.pConfig.hasOwnProperty('publicKey')
            && config.pConfig.hasOwnProperty('privateKey') && Array.isArray(config.pConfig.privateKey)
            && config.pConfig.privateKey.length > 0) {
          return [config.pConfig.publicKey, config.pConfig.privateKey[0]];
        }
      }
    }
    const publicKey = (new Date).getTime();
    const DEFAULT_PRIVATE_KEYS = ["version001", "vers1on001", "vers1on00i", "bersion001", "vcrsion001", "versi0n001", "versio_001", "version0o1"];
    const privateKey = DEFAULT_PRIVATE_KEYS[publicKey % DEFAULT_PRIVATE_KEYS.length];
    return [publicKey, privateKey];
  }

}
// Registry.registerClass("IyfInfo", new IyfInfo());